package servlet;

import bean.Result;
import biz.BizException;
import biz.CartBiz;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "CommitCartServlet", value = "/CommitCartServlet.s")
public class CommitCartServlet extends HttpServlet {
    private CartBiz biz = new CartBiz();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Result result;
        String json;
        // 需要的参数 uid, name, telphone, address, product,method, amount, total
        HttpSession session = request.getSession();
        String uid = String.valueOf(session.getAttribute("userid")); // 用户id
        if ( uid == null || uid.trim().isEmpty() || "null".equals(uid))  {
            result = new Result(0, "用户未登录", "login/Login-M.html");
            json = new Gson().toJson(result);
            response.getWriter().append(json);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Result result;
        String json;
        // 需要的参数 uid, name, telphone, address, product,method, amount, total
        HttpSession session = request.getSession();
        String uid = String.valueOf(session.getAttribute("userid")); // 用户id
        String name = request.getParameter("name");           // 收货人姓名
        String telphone = request.getParameter("telphone");   // 收货人电话号码
        String address = request.getParameter("address");     // 收货人地址
        String[] products = request.getParameterValues("product");// 购买商品
        String[] amounts = request.getParameterValues("amount");       // 购买的数量
        String method = request.getParameter("method");       // 支付方式
        String total = request.getParameter("total");         // 购买的总数
        String buy = request.getParameter("buy");
        System.out.println(name);
        System.out.println(telphone);
        System.out.println(amounts[0]);
        try {

            // 确认收货地址
            biz.queryAddress(uid, name, telphone, address);
            // 生成订单
            biz.createOrder(uid, total, address, method, telphone);
            if (buy != null){
                biz.modify(uid,products[0],amounts[0]);
                biz.createItem(uid, products[0], amounts[0]);
            }else{
                // 生成订单明细
                for (int i = 0; i < products.length; i++){
                    biz.createItem(uid,products[i], amounts[i]);
                    // 删除购物车
                    biz.removeCart(uid, products[i]);
                }
            }
            result = new Result(1, "购买成功", null);
        } catch (BizException e) {
            e.printStackTrace();
            result = new Result(0, e.getMessage(), null);
        }
        json = new Gson().toJson(result);
        response.getWriter().append(json);
    }
}
